#!/bin/bash -e

function info() {
echo Usage: `basename $0` '[-e test_data -n num_filt -l region_within] test'
exit 1
}

while getopts  ":p:f:e:n:l:" opt; do
	case  $opt  in
		p) out_prefix=$OPTARG;;
		f) suffix=$OPTARG;;
        e) tes=$OPTARG;;
        n) num_filt=$OPTARG;;
        l) len=$OPTARG;;
		*) info;;
	esac
done
shift $(($OPTIND - 1))

if [ $# -lt 1 ]; then info; fi

. $var

echo $tes

if test -n "$tes"; then
    bed=$data/bed/450.merge.100.3.bed
    trans.sh -t -p$out_prefix $tes
    b450_no_class=${out_prefix}_
    cut -f1 $tes > $out_prefix.id.test.txt
    b450_id=$out_prefix.id.test.txt
else
    bed=$data/bed/450.clean.b37.bed
    b450_no_class=$data/meth/b450k.sub.no_name.txt
    b450_id=$data/meth/450.id
fi


len=${len:=100}
num=${num_filt:=3}
# b450_no_class=$data/meth/b450k.no_name.txt
# b450_id=$data/meth/450.id
id_change=$data/bed/id_change

pos_b450.py -p$out_prefix $b450_id $bed
sort -k1,1 -k2,2n $out_prefix.pos.b450.txt > $out_prefix.pos.b450.sort.bed

for i in `seq 22` X Y; do 
    awk '$1~/^'"$i"'$/' $out_prefix.pos.b450.sort.bed > $out_prefix.$i
    
    if test -s $out_prefix.$i; then
        rf_change_region1.py -p$out_prefix.$i -n$num -l$len $out_prefix.$i
        cut -f4-5 $out_prefix.$i.$len.$num.bed > $out_prefix.id.$i
        cut -f5 $out_prefix.$i.$len.$num.bed > $out_prefix.$i.id

        if test -s $out_prefix.$i.id; then
            id_position.py -p$out_prefix $b450_id $out_prefix.$i.id; 

            cut -f1 $out_prefix.pos.$out_prefix.$i.id.txt|awk 'BEGIN{ORS=","}{print}'|sed '$s/,$/\n/' > $out_prefix.pos.$i.f.txt

            pos=`cat $out_prefix.pos.$i.f.txt`
            cut -f$pos $b450_no_class > $out_prefix.450.sub.$i.txt

            train_merge.py -p$out_prefix $out_prefix.450.sub.$i.txt $out_prefix.id.$i
        fi
    fi
done

if test -n "$tes"; then
    for i in `seq 22` X Y; do
        if test -s $out_prefix.$out_prefix.450.sub.$i.txt.txt; then
            trans.sh -p$out_prefix.$out_prefix.450.sub.$i.txt.txt $out_prefix.$out_prefix.450.sub.$i.txt.txt
        fi
    done
    cat $out_prefix.$out_prefix.450.sub.*.txt_ > $out_prefix.test.merge.$len.$num.txt
else
    paste $out_prefix.$out_prefix.450.sub.*.txt > $out_prefix.450.sub.merge.txt
fi

. $cmd_done